const path = require("path")
const _ = require("lodash")
const slugify = require("slugify")
const url = require("url")
const moment = require("moment")
const { slash } = require("gatsby-core-utils")

const docSlugFromPath = parsedFilePath => {
  if (parsedFilePath.name !== `index` && parsedFilePath.dir !== ``) {
    return `/${parsedFilePath.dir}/${parsedFilePath.name}/`
  } else if (parsedFilePath.dir === ``) {
    return `/${parsedFilePath.name}/`
  } else {
    return `/${parsedFilePath.dir}/`
  }
}
exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions

  const docsTemplate = path.resolve(`src/templates/template-docs-markdown.tsx`)

  const { data, errors } = await graphql(`
  query {
    allMdx {
      nodes {
        fields {
          slug
        }
        body
      }
    }
  }
  `)

  if (errors) {
    throw errors
  }

  _.forEach(data.allMdx.nodes, node => {
    if (node.fields.slug) {
      createPage({
        path: node.fields.slug,
        component: slash(docsTemplate),
        context: {
          slug: node.fields.slug,
        },
      })
    } else {
      /* createPage({
         path: node.fields.slug,
         component: slash(docsTemplate),
         context: {
           slug: node.fields.slug,
         },
       })*/
    }
  })

}


exports.onCreateNode = ({ node, actions, getNode }) => {
  const { createNodeField } = actions
  if ([`MarkdownRemark`, `Mdx`].includes(node.internal.type)) {
    const slug = _.get(node, `frontmatter.path`)
    createNodeField({ node, name: `slug`, value: slug })
  }
}
